package pay.portal;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.annotations.common.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import pay.base.BaseCtrl;
import pay.common.ConstantFYJZH;
import pay.entity.SysUser;
import pay.entity.Trade;
import pay.service.*;
import pay.service.sys.ISysUser;
import pay.utils.ConstantPush;
import pay.utils.MsgTypeConstants;

/**
 * 充值提现接口
 * 
 * @author jeff
 *
 */

@Controller
@EnableAutoConfiguration
@RequestMapping(value = BaseCtrl.App)
public class RechargeCtrl extends BaseCtrl {
	@Autowired
	private ISysUser sysUserService;

	@Value("${server.scheme}")
	private String serverScheme;

	@Value("${fy.goldAccount.pathBaseUrl}")
	private String pathBaseUrl;// 测试环境为/jzh 生产无。

	@Value("${server.url}")
	private String serverUrl;

	@Value("${fy.rechargeLogFilePath}")
	private String logFilePath;

	@Autowired
	private ITrade tradeService;

	@Autowired
	private IMessageService messageService;

	@Autowired
	private IUserCache  userCacheService;

	@Autowired
	private IFYResultCode fyResultCodeService;



	@ResponseBody
	@RequestMapping(value = "/recharge", produces = "application/json;charset=UTF8", method = RequestMethod.POST)
	public void reCharge(HttpServletRequest request,
			HttpServletResponse response) {
		String responseMsg = "";

		String responseCode = "";
		logger.info("进入富友充值函数");

		// 响应码
		String resp_code = request.getParameter("resp_code");
		// 响应消息
		String resp_desc = request.getParameter("resp_desc");

		// 商户代码,强制
		String mchnt_cd = request.getParameter("mchnt_cd");

		// 流水号， 强制
		String mchnt_txn_ssn = request.getParameter("mchnt_txn_ssn");

		// 交易用户
		String login_id = request.getParameter("login_id");

		// 交易金额,以分为单位 (无小数位)
		String amt = request.getParameter("amt");

		// 签名数据
		String signature = request.getParameter("signature");

		logger.info(
				"富友充值回调函数, 返回的参数是入：resp_code={}，resp_desc={}， mchnt_cd={}，mchnt_txn_ssn={}，login_id={}， amt={}",
				resp_code, resp_desc, mchnt_cd, mchnt_txn_ssn, login_id, amt);
		if (StringHelper.isEmpty(resp_code) || StringHelper.isEmpty(mchnt_cd)
				|| StringHelper.isEmpty(mchnt_txn_ssn)
				|| StringHelper.isEmpty(login_id) || StringHelper.isEmpty(amt)
				|| StringHelper.isEmpty(signature)) {
			logger.info("ChongZhiCtrl、Chongzhi 入参有值为空！");
			responseMsg = "传入参数不完整";
			reDirect(response, responseMsg, responseCode, mchnt_txn_ssn);
			return;
		}

		SysUser user = sysUserService.getByPhoneNum(login_id);
		Trade trade = new Trade();
		trade.setType(ConstantFYJZH.TRADE_TY_CZ);
		trade.setFlowType(ConstantFYJZH.BALANCE_ADD);
		trade.setMchnt_txn_ssn(mchnt_txn_ssn);
		trade.setLogin_id(login_id);
		trade.setResp_code(resp_code);
		trade.setResp_desc(resp_desc);
		trade.setAmt(new BigDecimal(amt).divide(new BigDecimal(100)));
		trade.setTradeDesc("充值");
		trade.setCts(System.currentTimeMillis());
		// 02 首先判断用户是否存在
		if (user == null) {
			logger.info("用户不存在 手机号={}", login_id);
			responseMsg = "用户不存在！";
			reDirect(response, responseMsg, responseCode, mchnt_txn_ssn);
			return ;
		} else {
			trade.setUserId(user.getId());
		}

		try {
			tradeService.writeTradeFile(trade, logFilePath);
		} catch (Exception e) {
			logger.error("充值写交易流水文件异常！", e);
		}
		tradeService.save(trade);

		if (resp_code.equalsIgnoreCase("0000")) {

			//充值成功，清除用户投资资产缓存
			try{
				userCacheService.removeUserAssetCache(user.getId());
			}catch (Exception e){
				logger.info("充值成功，删除用户投资资产缓存错误 error={}", e);
			}

			logger.info("充值成功 用户Id={},手机号={}, 充值结果={}", user.getId(), login_id,
					resp_code);
			responseMsg = "充值成功！";

			String msg = String.format("您已成功充值一笔%s元的资金到您的余额账户，请到投资资产中查看", trade.getAmt());
			this.messageService.sendMsg(String.valueOf(user.getId()), msg, "充值成功", ConstantPush.RESERVATION, MsgTypeConstants.RECHARGE);
		} else {
			logger.info("充值不成功手机号={}, 充值结果={}", login_id, resp_code);
			responseMsg = "充值失败！";
		}

		reDirect(response, responseMsg, resp_code, mchnt_txn_ssn);

	}


	// 进行页面跳转
	public void reDirect(HttpServletResponse response, String responseMsg,
			String responseCode, String mchnt_txn_ssn) {

		String codeMsg = fyResultCodeService.getCodeMsg(responseCode);

		if(codeMsg != null){
			responseMsg = codeMsg;
		}

		logger.info("responseMsg = {}", responseMsg);

		try {
			responseMsg = URLEncoder.encode(responseMsg, "utf-8");
			
			String url = serverScheme + "://" + serverUrl
					+ "/pays/rechargeResult.html?responseMsg=" + responseMsg
					+ "&responseCode=" + responseCode + "&mchnt_txn_ssn=" + mchnt_txn_ssn;
			logger.info("sendRedirect url={}", url);
			response.sendRedirect(url);
		} catch (UnsupportedEncodingException e) {
			logger.error("充值跳转页面异常！", e);
		} catch (IOException e) {
			logger.error("充值跳转页面异常！", e);
		}
	}

}
